<template>
    <header>
        <div class="header-return" @click="goBack">
            <i class="iconfont icon-fanhui"></i>
        </div>
        <div class="search-main">
            <i class="iconfont icon-sousuo"></i>
            <form action="" onsubmit="return false" @keyup.enter="goSearchList">
                <input type="search" placeholder="搜索你喜欢的产品" v-model="searchValue">
            </form>
        </div>
        <div class="search-btn" @click="goSearchList">
            搜索
        </div>
    </header>
</template>

<script>
export default {
    name:'SearchHeader',
    data () {
        return {
            searchValue:this.$route.query.key || '',
            searchArr:[]    
        }
    },
    methods: {
        goBack(){
            this.$router.back();
        },
        goSearchList(){
            //如果搜索的关键字是空白
            if(!this.searchValue) return;
            //判断之前有没有搜索的本地存储
            if(!localStorage.getItem('searchList')){
                //没有
                localStorage.setItem('searchList','[]');
            }else{
                this.searchArr = JSON.parse(localStorage.getItem('searchList')) ;
            }
            //增加数据
            this.searchArr.unshift(this.searchValue);
            //Es6 去重
            let newArr = new Set(this.searchArr);

            //给本地存储赋值
            localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)));
            
            // 路径如果没有变化（即搜索关键词没变化），就不跳转 
            if(this.searchValue === this.$route.query.key) return;
            //跳转页面
            this.$router.push({
                name:'Search-list',
                query:{
                    key:this.searchValue
                }
            });
        }
    }
}
</script>

<style>
header{width: 100%;height: 1.173333rem;display: flex;justify-content: space-around;align-items: center;background: #b0352f;color: #fff;}
.header-return{padding:0 .266667rem;}
.header-return i{font-size: .746667rem;}
.search-btn{font-size: .426667rem;padding: 0 .266667rem;}
.search-main{background: #fff;border-radius: 12px;display: flex;align-items: center;width: 6.933333rem;height: .8rem;}
.search-main i{color: #666;padding: 0 .266667rem;}
.search-main form{display: flex;justify-content: center;align-items: center;flex: 1;padding-right: .16rem;}
.search-main form input{width: 100%;height: 100%;}
</style>